import $ from 'jquery'
import axios from '@/until/fetch'

/* eslint-disable */
function ajaxImg(imgBase64, callback) {
  let newImg = convertBase64UrlToBlob(imgBase64)
  let formData = new FormData()

  formData.append("upload", 1)
  formData.append("upfile", newImg, Date.now() + '.jpg')
  axios.imgUpload('/api/Filse/UpLoadHeadImg', formData)
    .then((response) => {
      const res = response.data
      callback(imgBase64)
    })
    .catch((err) => {
      console.log(err)
    })
}

function convertBase64UrlToBlob(urlData) {
    var arr = urlData.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

// 请求方式的配置
export default {
  imagePost(e, callback) { // post
    if (e.target.files[0]) {
      let file = e.target.files[0]
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = function() {
        img.src = this.result
      }
      let img = new Image
      let width = 1024 // image resize   压缩后的宽
      let quality = 0.8 // image quality  压缩质量
      let canvas = document.createElement("canvas")
      let drawer = canvas.getContext("2d")
      img.onload = function() {
        canvas.width = width
        canvas.height = width * (img.height / img.width)
        drawer.drawImage(img, 0, 0, canvas.width, canvas.height)
        //上传到七牛云
        let base64 = canvas.toDataURL("image/jpeg", quality) // 这里就拿到了压缩后的base64图片
        ajaxImg(base64, callback)
        // var pic = base64.split(',')[1]
        // var url = "http://upload-z2.qiniu.com/putb64/-1"
        // var xhr = new XMLHttpRequest()
        // xhr.onreadystatechange = function() {
        //   if (xhr.readyState == 4) {
        //     that.imgs.push(JSON.parse(xhr.responseText).data.key)
        //   }
        // }
        // xhr.open("POST", url, true)
        // xhr.setRequestHeader("Content-Type", "application/octet-stream")
        // xhr.setRequestHeader("Authorization", "UpToken " + ‘七牛云token’)
        // xhr.send(pic)
        // // 清空文件上传控件的值  不清理会出现选择同样的图片会无法触发input事件了
        // e.target.value = null
      }
    }
  }
}
/* eslint-enable */
